package com.jty.lib_base.extension

import android.graphics.drawable.Drawable
import android.widget.ImageView
import androidx.annotation.DrawableRes
import com.blankj.utilcode.util.ResourceUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.jty.lib_base.R
import jp.wasabeef.glide.transformations.RoundedCornersTransformation


/**
 * author: zhouyh
 * created on: 2021/9/19 12:33 下午
 * description:ImageView扩展函数
 */
fun ImageView.loadImage(url: String) {
    Glide.with(this).load(url).apply(
        RequestOptions().diskCacheStrategy(DiskCacheStrategy.NONE)
            .skipMemoryCache(true)
            .dontAnimate()
            .placeholder(R.drawable.ic_placeholder)
    ).thumbnail(0.6f)  //进行压缩
        .into(this)
}

//加载手写笔记图片，不需要缓存
fun ImageView.loadNoteUrl(url: String){
//    Glide.with(this).load(url).apply(
//        RequestOptions().diskCacheStrategy(DiskCacheStrategy.NONE)   //不能用原始图，因为图片会改变
//            .skipMemoryCache(true)
//            .dontAnimate()
//    ).thumbnail(0.6f)
//        .into(this)
    Glide.with(this)
        .load(url)
        .apply(RequestOptions().diskCacheStrategy(DiskCacheStrategy.NONE).skipMemoryCache(true))
        .into(this)
}

/**
 * 加入图片 默认有缓存
 */
fun ImageView.loadPhotoUrl(url: String){
    Glide.with(this)
        .load(url)
        .into(this)
}

fun ImageView.loadUrl(url: String?, placeHolderRes: Drawable, errorHolder: Drawable?= ResourceUtils.getDrawable(R.drawable.ic_error_placeholder)){
    Glide.with(this)
        .load(url)
        .apply(
            RequestOptions().diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
                .placeholder(placeHolderRes).error(errorHolder)
        )
        .into(this)
}

fun ImageView.loadUrl(url: String?, placeHolderRes: Drawable){
    Glide.with(this)
        .load(url)
        .apply(
            RequestOptions().placeholder(placeHolderRes)
        )
        .into(this)
}

fun ImageView.loadDefault(default: Drawable){
    Glide.with(this).load(default).into(this)
}


/**
 * 圆角
 */
fun ImageView.loadRoundImage(url: String?, radius: Int, @DrawableRes holder: Int? = null) {
    if (url.isNullOrBlank() && holder != null) {
        setImageResource(holder)
    } else if (holder == null) {
        Glide.with(this).load(url)
            .apply(RequestOptions.bitmapTransform(RoundedCornersTransformation(radius, 0)))
            .into(this)
    } else {
        Glide.with(this).load(url).apply(
            RequestOptions.bitmapTransform(RoundedCornersTransformation(radius, 0))
                .placeholder(holder)
        )
            .into(this)
    }
}


